package br.com.social.mobile.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import br.com.social.mobile.entities.Position;


public class PositionDAO extends GenericDAO<Position>{
	
	private Logger logger = Logger.getLogger(PositionDAO.class);
	
	
    public List<Position> listPosition() {
    	
//    	SELECT P.*
//    	FROM TB_POSITION P
//    	INNER JOIN
//    	    (SELECT NU_IMEI, MAX(DT_POSITION) AS MaxDateTime
//    	    FROM TB_POSITION
//    	    GROUP BY NU_IMEI) P2
//    	ON P.NU_IMEI = P2.NU_IMEI 
//    	AND P.DT_POSITION = P2.MaxDateTime
    	

    	
    	createEntityManager();
    	@SuppressWarnings("unchecked")
		List<Object> lstObject = entityManager.createQuery("select p, max(p.id) FROM Position p group by p.nuImei").getResultList();
    	List<Position> lstPosition = new ArrayList<Position>();
    	Position position;
    	for (Iterator<?> iterator = lstObject.iterator(); iterator.hasNext();) {
			@SuppressWarnings("unchecked")
			Object[] object = (Object[]) iterator.next();
			position = getById((Long) object[1]);
			
			lstPosition.add(position);
		}    	
    	
    	
        return lstPosition;
    }		
    
    public List<Position> maxSpeedGroupByUser() {
    	
    	createEntityManager();
    	@SuppressWarnings("unchecked")
		List<Object> lstObject = entityManager.createQuery("select p, max(p.nuSpeed) FROM Position p group by p.nuImei").getResultList();
    	List<Position> lstPosition = new ArrayList<Position>();
    	Position position;
    	for (Iterator<?> iterator = lstObject.iterator(); iterator.hasNext();) {
			@SuppressWarnings("unchecked")
			Object[] object = (Object[]) iterator.next();
			position = (Position)object[0];
			position.setNuSpeed((Double) object[1]);
			lstPosition.add(position);
		}    	
    	
    	
        return lstPosition;
    }		
 
}
